<template>
	<div class="drug-management">
		<!-- 顶部操作栏 -->
		<div class="operation-bar">
			<div class="left-section">
				<el-button type="primary" icon="el-icon-plus" @click="handleAdd" size="medium" class="add-btn">
					新增药品
				</el-button>
				<el-button type="success" icon="el-icon-refresh" @click="refreshData" :loading="loading" size="medium">
					刷新
				</el-button>
			</div>

			<div class="right-section">
				<el-input v-model="searchKeyword" placeholder="搜索药品名称/编码" prefix-icon="el-icon-search"
					style="width: 200px; margin-right: 10px;" size="medium" clearable @input="handleSearch" />

				<el-select v-model="filter.drugForm" placeholder="剂型" clearable style="width: 120px;" size="medium"
					@change="handleFilter">
					<el-option label="全部剂型" value=""></el-option>
					<el-option v-for="form in drugForms" :key="form" :label="form" :value="form" />
				</el-select>

				<el-select v-model="filter.drugType" placeholder="药品类型" clearable
					style="width: 120px; margin-left: 10px;" size="medium" @change="handleFilter">
					<el-option label="全部类型" value=""></el-option>
					<el-option label="西药" value="西药"></el-option>
					<el-option label="中药" value="中药"></el-option>
					<el-option label="中成药" value="中成药"></el-option>
					<el-option label="生物制品" value="生物制品"></el-option>
				</el-select>
			</div>
		</div>

		<!-- 药品表格 -->
		<div class="drug-table-container">
			<el-table :data="filteredDrugList" v-loading="loading" style="width: 100%" border stripe
				:default-sort="{prop: 'drugCode', order: 'ascending'}" @sort-change="handleSortChange"
				class="drug-table">
				<el-table-column type="index" label="序号" width="70" align="center" />

				<el-table-column prop="drugCode" label="药品编码" width="120" sortable align="center">
					<template slot-scope="{ row }">
						<span v-if="row.isEditing">
							<el-input v-model="row.editForm.drugCode" size="small" maxlength="20" :disabled="true"
								class="edit-input" />
						</span>
						<span v-else class="drug-code">
							<el-tag size="mini" type="info" effect="dark">{{ row.drugCode }}</el-tag>
						</span>
					</template>
				</el-table-column>

				<el-table-column prop="drugName" label="药品名称" min-width="220" sortable>
					<template slot-scope="{ row }">
						<div v-if="row.isEditing" class="edit-cell">
							<el-input v-model="row.editForm.drugName" size="small" placeholder="请输入药品名称"
								class="edit-input" />
						</div>
						<div v-else class="drug-info">
							<span class="drug-name">{{ row.drugName }}</span>
							<el-tag v-if="row.drugType" size="mini" :type="getDrugTypeTag(row.drugType)"
								class="drug-type-tag">
								{{ row.drugType }}
							</el-tag>
						</div>
					</template>
				</el-table-column>

				<el-table-column prop="drugSpec" label="规格" width="120" align="center">
					<template slot-scope="{ row }">
						<span v-if="row.isEditing">
							<el-input v-model="row.editForm.drugSpec" size="small" placeholder="如：0.25g"
								class="edit-input" />
						</span>
						<span v-else class="drug-spec">
							{{ row.drugSpec }}
						</span>
					</template>
				</el-table-column>

				<el-table-column prop="drugUnit" label="单位" width="100" align="center">
					<template slot-scope="{ row }">
						<span v-if="row.isEditing">
							<el-select v-model="row.editForm.drugUnit" size="small" class="edit-select"
								placeholder="选择单位">
								<el-option label="粒" value="粒"></el-option>
								<el-option label="片" value="片"></el-option>
								<el-option label="支" value="支"></el-option>
								<el-option label="瓶" value="瓶"></el-option>
								<el-option label="盒" value="盒"></el-option>
								<el-option label="袋" value="袋"></el-option>
								<el-option label="g" value="g"></el-option>
								<el-option label="mg" value="mg"></el-option>
								<el-option label="ml" value="ml"></el-option>
								<el-option label="L" value="L"></el-option>
							</el-select>
						</span>
						<span v-else class="drug-unit">
							{{ row.drugUnit }}
						</span>
					</template>
				</el-table-column>

				<el-table-column prop="drugForm" label="剂型" width="120" align="center">
					<template slot-scope="{ row }">
						<span v-if="row.isEditing">
							<el-select v-model="row.editForm.drugForm" size="small" class="edit-select"
								placeholder="选择剂型">
								<el-option v-for="form in drugForms" :key="form" :label="form" :value="form" />
							</el-select>
						</span>
						<span v-else>
							<el-tag :type="getDrugFormTag(row.drugForm)" size="small" effect="plain">
								{{ row.drugForm }}
							</el-tag>
						</span>
					</template>
				</el-table-column>

				<el-table-column prop="drugType" label="药品类型" width="100" align="center">
					<template slot-scope="{ row }">
						<span v-if="row.isEditing">
							<el-select v-model="row.editForm.drugType" size="small" class="edit-select">
								<el-option label="西药" value="西药"></el-option>
								<el-option label="中药" value="中药"></el-option>
								<el-option label="中成药" value="中成药"></el-option>
								<el-option label="生物制品" value="生物制品"></el-option>
							</el-select>
						</span>
						<span v-else>
							<el-tag :type="getDrugTypeTag(row.drugType)" size="small" effect="plain">
								{{ row.drugType || '--' }}
							</el-tag>
						</span>
					</template>
				</el-table-column>


				<el-table-column label="操作" width="180" align="center" fixed="right">
					<template slot-scope="{ row }">
						<div class="action-buttons">
							<template v-if="row.isEditing">
								<el-button type="success" size="mini" icon="el-icon-check" @click="saveDrug(row)"
									:loading="row.saving" class="save-btn">
									保存
								</el-button>
								<el-button type="info" size="mini" icon="el-icon-close" @click="cancelEdit(row)"
									:disabled="row.saving">
									取消
								</el-button>
							</template>
							<template v-else>
								<el-button type="primary" size="mini" icon="el-icon-edit" @click="startEdit(row)"
									:disabled="editingRow && editingRow !== row" class="edit-btn">
									编辑
								</el-button>
								<el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteDrug(row)"
									class="delete-btn">
									删除
								</el-button>
							</template>
						</div>
					</template>
				</el-table-column>
			</el-table>

			<!-- 数据为空提示 -->
			<div v-if="!loading && filteredDrugList.length === 0" class="empty-tips">
				<el-empty description="暂无药品数据" v-if="searchKeyword || filter.drugForm || filter.drugType">
					<el-button type="primary" @click="clearFilters">清除筛选条件</el-button>
				</el-empty>
				<el-empty description="暂无药品数据，点击新增按钮添加" v-else>
					<el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增药品</el-button>
				</el-empty>
			</div>
		</div>

		<!-- 新增/编辑药品对话框 -->
		<el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" @closed="handleDialogClosed"
			:close-on-click-modal="false">
			<el-form ref="drugForm" :model="formData" :rules="rules" label-width="100px" class="drug-form">
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="药品编码" prop="drugCode">
							<el-input v-model="formData.drugCode" placeholder="如：1000001" maxlength="20"
								show-word-limit />
							<div class="form-tip">药品唯一编码，创建后不可修改</div>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="药品类型" prop="drugType">
							<el-select v-model="formData.drugType" placeholder="选择药品类型" style="width: 100%">
								<el-option label="西药" value="西药"></el-option>
								<el-option label="中药" value="中药"></el-option>
								<el-option label="中成药" value="中成药"></el-option>
								<el-option label="生物制品" value="生物制品"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<el-form-item label="药品名称" prop="drugName">
					<el-input v-model="formData.drugName" placeholder="请输入药品名称" maxlength="100" show-word-limit />
				</el-form-item>

				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="规格" prop="drugSpec">
							<el-input v-model="formData.drugSpec" placeholder="如：0.25g" maxlength="50"
								show-word-limit />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="单位" prop="drugUnit">
							<el-select v-model="formData.drugUnit" placeholder="选择单位" style="width: 100%" filterable
								allow-create>
								<el-option label="粒" value="粒"></el-option>
								<el-option label="片" value="片"></el-option>
								<el-option label="支" value="支"></el-option>
								<el-option label="瓶" value="瓶"></el-option>
								<el-option label="盒" value="盒"></el-option>
								<el-option label="袋" value="袋"></el-option>
								<el-option label="g" value="g"></el-option>
								<el-option label="mg" value="mg"></el-option>
								<el-option label="ml" value="ml"></el-option>
								<el-option label="L" value="L"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="剂型" prop="drugForm">
							<el-select v-model="formData.drugForm" placeholder="选择剂型" style="width: 100%" filterable
								allow-create>
								<el-option label="胶囊剂" value="胶囊剂"></el-option>
								<el-option label="片剂" value="片剂"></el-option>
								<el-option label="注射剂" value="注射剂"></el-option>
								<el-option label="颗粒剂" value="颗粒剂"></el-option>
								<el-option label="口服液" value="口服液"></el-option>
								<el-option label="软膏剂" value="软膏剂"></el-option>
								<el-option label="栓剂" value="栓剂"></el-option>
								<el-option label="喷雾剂" value="喷雾剂"></el-option>
								<el-option label="贴剂" value="贴剂"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>

			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false" :disabled="submitting">
					取消
				</el-button>
				<el-button type="primary" @click="submitForm" :loading="submitting">
					确定
				</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import http from '../../utils/request'

	export default {
		name: 'DrugManagement',
		data() {
			// 验证药品编码
			const validateDrugCode = (rule, value, callback) => {
				if (!value) {
					callback(new Error('药品编码不能为空'))
					return
				}

				// 编码格式：字母数字组合
				const codePattern = /^[A-Za-z0-9]+$/
				if (!codePattern.test(value)) {
					callback(new Error('药品编码只能包含字母和数字'))
					return
				}

				// 检查编码是否重复（新增时检查）
				if (!this.isEditMode) {
					const exists = this.originalDrugList.some(drug => drug.drugCode === value)
					if (exists) {
						callback(new Error('该药品编码已存在'))
						return
					}
				}

				callback()
			}

			return {
				// 数据
				originalDrugList: [],
				loading: false,

				// 搜索和筛选
				searchKeyword: '',
				filter: {
					drugForm: '',
					drugType: ''
				},

				// 编辑状态
				editingRow: null,
				isEditMode: false,

				// 对话框相关
				dialogVisible: false,
				submitting: false,
				dialogTitle: '新增药品',
				formData: {
					drugCode: '',
					drugName: '',
					drugSpec: '',
					drugUnit: '粒',
					drugForm: '胶囊剂',
					drugType: '西药',
				},

				// 剂型列表（从数据中提取）
				drugForms: [],

				// 表单验证规则
				rules: {
					drugCode: [{
						required: true,
						validator: validateDrugCode,
						trigger: 'blur'
					}],
					drugName: [{
							required: true,
							message: '请输入药品名称',
							trigger: 'blur'
						},
						{
							min: 2,
							max: 100,
							message: '长度在 2 到 100 个字符',
							trigger: 'blur'
						}
					],
					drugSpec: [{
						required: true,
						message: '请输入药品规格',
						trigger: 'blur'
					}],
					drugUnit: [{
						required: true,
						message: '请选择药品单位',
						trigger: 'change'
					}],
					drugForm: [{
						required: true,
						message: '请选择药品剂型',
						trigger: 'change'
					}],
					drugType: [{
						required: true,
						message: '请选择药品类型',
						trigger: 'change'
					}]
				}
			}
		},

		computed: {
			// 计算过滤后的药品列表
			filteredDrugList() {
				let list = this.originalDrugList

				// 关键词搜索
				if (this.searchKeyword) {
					const keyword = this.searchKeyword.toLowerCase()
					list = list.filter(item =>
						item.drugName.toLowerCase().includes(keyword) ||
						item.drugCode.toLowerCase().includes(keyword) 
					)
				}

				// 剂型筛选
				if (this.filter.drugForm) {
					list = list.filter(item => item.drugForm === this.filter.drugForm)
				}

				// 类型筛选
				if (this.filter.drugType) {
					list = list.filter(item => item.drugType === this.filter.drugType)
				}

				return list
			}
		},

		async created() {
			await this.loadDrugData()
		},

		methods: {
			// 加载药品数据
			async loadDrugData() {
				this.loading = true
				try {
					const resp = await http.get('/admin/getDrugList')
					if (resp.data.code === 1) {
						this.originalDrugList = resp.data.data.map(item => ({
							drugCode: item.drugCode,
							drugName: item.drugName,
							drugSpec: item.drugSpec,
							drugUnit: item.drugUnit,
							drugForm: item.drugForm,
							// 扩展字段（后端可能没有返回，这里设置默认值）
							drugType: '西药',
							// 编辑状态
							isEditing: false,
							saving: false,
							editForm: {}
						}))

						// 提取剂型列表
						this.extractDrugForms()

						// 按药品编码排序
						this.originalDrugList.sort((a, b) => a.drugCode.localeCompare(b.drugCode))
					} else {
						this.$message.error(resp.data.msg || '获取药品列表失败')
					}
				} catch (error) {
					this.$message.error('网络请求失败')
					console.error('加载药品数据失败:', error)
				} finally {
					this.loading = false
				}
			},

			// 提取剂型列表
			extractDrugForms() {
				const forms = new Set()
				this.originalDrugList.forEach(item => {
					if (item.drugForm) {
						forms.add(item.drugForm)
					}
				})
				this.drugForms = Array.from(forms).sort()
			},

			// 刷新数据
			refreshData() {
				this.searchKeyword = ''
				this.filter.drugForm = ''
				this.filter.drugType = ''
				this.loadDrugData()
			},

			// 搜索
			handleSearch() {
				// 实时搜索，无需额外处理
			},

			// 筛选
			handleFilter() {
				// 实时筛选，无需额外处理
			},

			// 清除筛选条件
			clearFilters() {
				this.searchKeyword = ''
				this.filter.drugForm = ''
				this.filter.drugType = ''
			},

			// 排序改变
			handleSortChange({
				prop,
				order
			}) {
				this.originalDrugList.sort((a, b) => {
					let aValue = a[prop]
					let bValue = b[prop]

					if (typeof aValue === 'string') {
						aValue = aValue.toLowerCase()
						bValue = bValue.toLowerCase()
					}

					if (aValue < bValue) {
						return order === 'ascending' ? -1 : 1
					}
					if (aValue > bValue) {
						return order === 'ascending' ? 1 : -1
					}
					return 0
				})
			},

			// 获取剂型标签样式
			getDrugFormTag(form) {
				const formMap = {
					'胶囊剂': 'success',
					'片剂': 'primary',
					'注射剂': 'danger',
					'颗粒剂': 'warning',
					'口服液': 'info',
					'软膏剂': 'success',
					'栓剂': 'primary',
					'喷雾剂': 'danger'
				}
				return formMap[form] || 'info'
			},

			// 获取药品类型标签样式
			getDrugTypeTag(type) {
				const typeMap = {
					'西药': 'primary',
					'中药': 'success',
					'中成药': 'warning',
					'生物制品': 'danger'
				}
				return typeMap[type] || 'info'
			},

			// 开始编辑
			startEdit(row) {
				// 确保同一时间只有一个在编辑
				if (this.editingRow && this.editingRow !== row) {
					this.$message.warning('请先完成当前编辑')
					return
				}

				this.cancelEdit(this.editingRow)

				row.isEditing = true
				row.editForm = {
					...row
				}
				this.editingRow = row
				this.isEditMode = true
			},

			// 保存编辑
			async saveDrug(row) {
				try {
					// 验证必填字段
					if (!row.editForm.drugName || !row.editForm.drugName.trim()) {
						this.$message.error('药品名称不能为空')
						return
					}

					if (!row.editForm.drugSpec || !row.editForm.drugSpec.trim()) {
						this.$message.error('药品规格不能为空')
						return
					}

					row.saving = true

					const response = await http.post('/admin/updateDrug', {
						drugCode: row.drugCode, // drugCode不可修改，使用原值
						drugName: row.editForm.drugName,
						drugSpec: row.editForm.drugSpec,
						drugUnit: row.editForm.drugUnit,
						drugForm: row.editForm.drugForm,
						drugType: row.editForm.drugType || '西药',
					})

					if (response.data.code === 1) {
						this.$message.success('保存成功')

						// 更新本地数据
						Object.assign(row, row.editForm)
						row.isEditing = false
						row.saving = false
						this.editingRow = null
						this.isEditMode = false

						// 更新剂型列表
						this.extractDrugForms()
					} else {
						this.$message.error(response.data.msg || '保存失败')
						row.saving = false
					}
				} catch (error) {
					this.$message.error('保存失败')
					row.saving = false
					console.error('保存药品信息失败:', error)
				}
			},

			// 取消编辑
			cancelEdit(row) {
				if (row) {
					row.isEditing = false
					row.saving = false
					row.editForm = {
						...row
					}
				}
				this.editingRow = null
				this.isEditMode = false
			},

			// 删除药品
			deleteDrug(row) {
				this.$confirm(`确定要删除药品【${row.drugName}】吗？`, '删除确认', {
					type: 'warning',
					confirmButtonText: '确定删除',
					cancelButtonText: '取消',
					confirmButtonClass: 'el-button--danger',
					center: true
				}).then(async () => {
					try {
						const response = await http.post('/admin/deleteDrug', {
							drugCode: row.drugCode
						})

						if (response.data.code === 1) {
							this.$message.success('删除成功')

							// 从列表中移除
							const index = this.originalDrugList.findIndex(item => item.drugCode === row
								.drugCode)
							if (index !== -1) {
								this.originalDrugList.splice(index, 1)
								this.extractDrugForms()
							}
						} else {
							this.$message.error(response.data.msg || '删除失败')
						}
					} catch (error) {
						this.$message.error('删除失败')
						console.error('删除药品失败:', error)
					}
				}).catch(() => {
					// 用户取消删除
				})
			},

			// 新增药品
			handleAdd() {
				this.cancelEdit(this.editingRow)
				this.isEditMode = false
				this.dialogTitle = '新增药品'
				this.formData = {
					drugCode: this.getNextDrugCode(),
					drugName: '',
					drugSpec: '',
					drugUnit: '粒',
					drugForm: '胶囊剂',
					drugType: '西药',
				}
				this.dialogVisible = true
			},

			// 获取下一个药品编码
			getNextDrugCode() {
				if (this.originalDrugList.length === 0) return '1000001'

				// 查找最大的数字编码
				let maxCode = 0
				this.originalDrugList.forEach(item => {
					const codeNum = parseInt(item.drugCode)
					if (!isNaN(codeNum) && codeNum > maxCode) {
						maxCode = codeNum
					}
				})

				return String(maxCode + 1).padStart(7, '0')
			},

			// 提交表单（新增）
			submitForm() {
				this.$refs.drugForm.validate(async (valid) => {
					if (!valid) return

					this.submitting = true

					try {
						const response = await http.post('/admin/addDrug', this.formData)

						if (response.data.code === 1) {
							this.$message.success('新增成功')
							this.dialogVisible = false
							await this.loadDrugData()
						} else {
							this.$message.error(response.data.msg || '新增失败')
						}
					} catch (error) {
						this.$message.error('新增失败')
						console.error('新增药品失败:', error)
					} finally {
						this.submitting = false
					}
				})
			},

			// 对话框关闭
			handleDialogClosed() {
				this.$refs.drugForm?.resetFields()
				this.submitting = false
			}
		}
	}
</script>

<style scoped>
	.drug-management {
		padding: 20px;
		background: #f0f2f5;
		min-height: calc(100vh - 60px);
	}

	.operation-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
		padding: 20px;
		background: white;
		border-radius: 8px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
	}

	.left-section {
		display: flex;
		gap: 10px;
	}

	.right-section {
		display: flex;
		align-items: center;
	}

	.add-btn {
		background: linear-gradient(135deg, #409EFF 0%, #337ecc 100%);
		border: none;
	}

	.drug-table-container {
		background: white;
		border-radius: 8px;
		padding: 20px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
		margin-bottom: 20px;
		min-height: 400px;
	}

	.drug-table {
		border-radius: 6px;
		overflow: hidden;
	}

	.drug-table :deep(.el-table__header-wrapper) {
		background: #fafafa;
	}

	.drug-table :deep(.el-table__body tr:hover) {
		background-color: #f5f7fa !important;
	}

	.drug-info {
		display: flex;
		align-items: center;
		gap: 8px;
		flex-wrap: wrap;
	}

	.drug-name {
		font-weight: 500;
		color: #303133;
	}

	.drug-type-tag {
		font-size: 10px;
		padding: 0 4px;
		height: 18px;
		line-height: 18px;
	}

	.drug-code {
		font-family: 'Consolas', monospace;
		font-weight: 600;
		color: #409EFF;
	}

	.drug-spec,
	.drug-unit {
		font-weight: 500;
		color: #606266;
	}

	.empty-text {
		color: #909399;
		font-style: italic;
	}

	.action-buttons {
		display: flex;
		gap: 6px;
		justify-content: center;
	}

	.edit-input,
	.edit-select {
		width: 100%;
	}

	.empty-tips {
		padding: 40px 0;
		text-align: center;
	}

	.form-tip {
		font-size: 12px;
		color: #909399;
		margin-top: 5px;
	}

	.dialog-footer {
		text-align: right;
		padding-top: 20px;
		border-top: 1px solid #ebeef5;
	}

	.drug-form .el-row {
		margin-bottom: 0;
	}

	:deep(.el-table__row) {
		transition: all 0.3s ease;
	}

	:deep(.el-table__row.is-editing) {
		background-color: #f0f9ff !important;
	}

	:deep(.el-table__row.is-editing:hover) {
		background-color: #e6f7ff !important;
	}

	:deep(.el-table__row .el-input__inner) {
		border-radius: 4px;
	}

	:deep(.el-table__row .el-select .el-input__inner) {
		border-radius: 4px;
	}
</style>